<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div class="">
      <div class="text-right p-2">
        <a-button type="primary" size="small" @click="handleAdd">新增</a-button>
      </div>
      <Table :dataSource="list" :columns="columns" :pagination="false">
        <template #tztj="{ record, index }">
          <div class="flex justify-between">
            <div>
              <Select
                :options="firstBracketOptions"
                v-model:value="record['beginBracket']"
                class="w-80px"
                style="margin-right: 5px"
              />

              <Select
                :options="fieldNameOptions"
                v-model:value="record['backField']"
                class="w-200px"
                style="margin-right: 5px"
                @change="(val) => getFieldName(val, record)"
              />
              <Select
                :options="compareOptions"
                v-model:value="record['compare']"
                class="w-80px"
                style="margin-right: 5px"
                v-if="
                  record['fieldType'] == FormField.FIELD_TYPE_DOUBLE ||
                  record['fieldType'] == FormField.FIELD_TYPE_FLOAT ||
                  record['fieldType'] == FormField.FIELD_TYPE_INT ||
                  record['fieldType'] == FormField.FIELD_TYPE_LONG ||
                  record['fieldType'] == FormField.FIELD_TYPE_PRICE
                "
              />
              <Select
                :options="compareOptions2"
                v-model:value="record['compare']"
                class="w-80px"
                style="margin-right: 5px"
                v-else
              />
            </div>
            <div class="w-300px">
              <div class="mb-2">
                <RadioGroup v-model:value="record.opType">
                  <radio value="custom">指定值</radio>
                  <radio value="main">主表值</radio>
                </RadioGroup>
              </div>
              <Input
                v-model:value="record.backFieldValue"
                v-if="
                  record['opType'] == 'custom' &&
                  (record['backField'] == 'id' || record['backField'] == 'cws_id' || type == 2)
                "
              />
              <FormCtl
                v-if="
                  record['opType'] == 'custom' &&
                  record['backField'] != 'id' &&
                  record['backField'] != 'cws_id' &&
                  type == 1
                "
                :formCode="record['formCode']"
                :fieldName="record['backField']"
                v-model:value="record['backFieldValue']"
              />
              <Select
                v-if="record['opType'] == 'main'"
                :options="concatFiels"
                v-model:value="record['backFieldValue']"
                class="w-full"
              />
            </div>
            <div>
              <Select
                :options="firstBracketOptions"
                v-model:value="record['endBracket']"
                class="w-80px inline-block"
                style="margin-right: 5px"
              />
              <Select
                :options="logicalOptions"
                v-model:value="record['logical']"
                class="w-80px inline-block"
                style="margin-right: 5px"
                v-if="index != list.length - 1"
              />
              <div class="w-80px inline-block" v-else></div>
            </div>
          </div>
        </template>
        <template #action="{ index }">
          <div class="flex">
            <a-button type="primary" class="mr-2" size="small" @click="handleAdd">新增</a-button>
            <a-button type="primary" size="small" @click="handleDelete(index)">删除</a-button>
          </div>
        </template>
      </Table>
      <div class="p-2">
        <div>注：条件中只支持一个子表</div>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { Table, Select, Radio, Input } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useFlowStore } from '/@/store/modules/flow';
  import { isArray } from '/@/utils/is';
  import { getRoleMultilSel } from '/@/api/system/system';

  import { FormCtl } from '/@/components/FormCtl';

  import {
    firstBracketOptions,
    columns,
    compareOptions,
    logicalOptions,
    compareOptions2,
  } from './configViewModal.data';
  import { FormField, WorkflowPredefineDb } from '/@/enums/flowManage';
  import { getFormGetNestFieldsWithFormName, getFormGetFields } from '/@/api/flowManage/flowManage';

  export default defineComponent({
    name: 'ConfigrationCombinationModal',
    components: {
      BasicModal,
      Table,
      Select,
      FormCtl,
      Radio,
      RadioGroup: Radio.Group,
      Input,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const useFlow = useFlowStore();
      const dataRef = ref<Recordable>({});
      const linkProps = ref('');
      const formData = ref<Recordable>({});
      const list = ref<any>([]);
      const getTitle = '配置';

      const fieldNameOptions: any = ref([]);
      const roleOptions: any = ref([]);
      const formCode = ref('');
      const type = ref(1);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '1200px' });
        try {
          formCode.value = data?.formCode;
          type.value = data?.type;
          list.value = data?.list ? [...data.list] : [];
          linkProps.value = useFlow?.flowEdit.linkProps;
          fieldNameOptions.value = [];
          if (isArray(data?.fields)) {
            if (unref(type) == 1) {
              data.fields.forEach((item) => {
                fieldNameOptions.value.push({
                  fieldType: item.fieldType,
                  macroType: item.macroType,
                  formCode: item.formCode,
                  type: item.type,
                  typeDesc: item.typeDesc,
                  value: item.name,
                  label: item.title,
                });
              });
              fieldNameOptions.value.push({
                fieldType: 0,
                macroType: '',
                formCode: 'archive_files',
                type: '',
                typeDesc: '',
                value: 'id',
                label: 'id',
              });
              fieldNameOptions.value.push({
                fieldType: 0,
                macroType: '',
                formCode: 'archive_files',
                type: '',
                typeDesc: '',
                value: 'cws_id',
                label: 'cws_id',
              });
            } else {
              fieldNameOptions.value = data.fields;
            }
          }
          getRoleMultilSelData();
          getNestFormFields();
          getMainFormFields();
          if (unref(list.value.length) == 0) {
            handleAdd();
          } else {
            list.value.forEach((item) => {
              const obj = fieldNameOptions.value.find((el) => el.value == item.backField);
              item['fieldType'] = obj?.fieldType;
              item['formCode'] = obj?.formCode;
            });
          }
          console.log({
            list: list.value,
            linkProps: linkProps.value,
            fieldNameOptions,
            fields: data?.fields,
            type: unref(type),
          });
        } catch (err) {
          console.log(err);
        }
      });

      const getRoleMultilSelData = async () => {
        await getRoleMultilSel().then((res) => {
          let data = res || [];
          data.forEach((item) => {
            item.value = item.code;
            item.label = item.description;
          });
          roleOptions.value = data;
        });
      };

      async function handleSubmit() {
        try {
          // setModalProps({ confirmLoading: true });

          let beginBracketArr: string[] = [];
          let endBracketArr: string[] = [];
          unref(list).forEach((item) => {
            if (item.beginBracket == '(' || item.endBracket == '(') {
              beginBracketArr.push('(');
            }
            if (item.beginBracket == ')' || item.endBracket == ')') {
              endBracketArr.push(')');
            }
          });
          if (beginBracketArr.length != endBracketArr.length) {
            return createMessage.warning('请检查括弧是否匹配');
          }
          if (unref(list).length && unref(list).some((item) => !item.backField)) {
            return createMessage.warning('请选择条件字段');
          }
          closeModal();
          emit('success', { list: [...unref(list)] });
        } catch (err) {
          console.log(err);
        } finally {
          // setModalProps({ confirmLoading: false });
        }
      }

      const handleAdd = () => {
        // const obj = isArray(fieldNameOptions.value) ? fieldNameOptions.value[0] : {};
        list.value.push({
          mainColumn: 'comb_field',
          backField: '', //obj?.value,
          fieldType: '', //obj?.fieldType,
          formCode: '', //obj?.formCode,
          columnName: '',
          compare: '=',
          beginBracket: '',
          value: '',
          endBracket: '',
          logical: 'and',
          opType: 'custom',
        });
        list.value = [...list.value];
      };
      const handleDelete = (index) => {
        list.value.splice(index, 1);
        list.value = [...list.value];
      };

      //选择表单
      const getFieldName = (val, record) => {
        if (val) {
          const obj = fieldNameOptions.value.find((item) => item.value == val);
          record['fieldType'] = obj?.fieldType;
          record['formCode'] = obj?.formCode;
        } else {
          record['fieldType'] = '';
          record['formCode'] = '';
        }
      };

      const fieldsWithNestList = ref([]);
      // 获取嵌套表字段
      async function getNestFormFields() {
        let params = {
          formCode: unref(formCode),
        };
        await getFormGetNestFieldsWithFormName(params).then((res) => {
          let data = res || [];
          let forms: any = [];
          let curNestForm = '';
          data.forEach((item, index) => {
            delete item.options;
            item.value = `{$nest.${item.formCode}.${item.name}}`;
            item.title = `${item.formName}-${item.title}`;
            item.label = item.title;

            if (item.formCode != curNestForm) {
              curNestForm = item.formCode;
              forms.push({ formCode: item.formCode, formName: item.formName, index: index - 1 });
            }
          });

          console.log('getNestFormFields forms', forms);
          console.log('getNestFormFields data', data);

          let nestFormCount = 0;
          forms.forEach((item) => {
            // 格式：{$nest.pur_cont_dtl.cws_quote_id}
            let quoteItem = {
              formCode: item.formCode,
              formName: item.formName,
              value: `{$nest.${item.formCode}.cws_quote_id}`,
              title: `${item.formName}-引用ID`,
              label: `${item.formName}-引用ID`,
            };
            nestFormCount++;
            data.splice(item.index + nestFormCount, 0, quoteItem);
          });
          fieldsWithNestList.value = data;
          console.log('getNestFormFields fieldsWithNestList.value', fieldsWithNestList.value);
        });
      }
      //主表字段
      const mainFormFields = ref<Recordable[]>([]);
      const getMainFormFields = async () => {
        let params = {
          formCode: unref(formCode),
        };
        await getFormGetFields(params).then((res) => {
          let data = res || [];
          data.forEach((item) => {
            delete item.options;
            item.value = `{$${item.title}}`;
            item.label = item.title;
          });
          data.unshift({ name: 'id', label: 'ID', title: 'ID', value: '{$id}' });
          mainFormFields.value = data;
        });
      };
      const concatFiels = computed(() => [...unref(mainFormFields), ...unref(fieldsWithNestList)]);
      return {
        registerModal,
        getTitle,
        handleSubmit,
        list,
        columns,
        firstBracketOptions,
        fieldNameOptions,
        compareOptions,
        roleOptions,
        logicalOptions,
        compareOptions2,
        WorkflowPredefineDb,
        handleAdd,
        handleDelete,
        getFieldName,
        FormField,
        concatFiels,
        type,
      };
    },
  });
</script>
